<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 300px; overflow-y: hidden;"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onChange="handleChange"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, defineComponent, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor } from '@wangeditor/editor';
import {fileView, uploadUrl} from "@/api/upload";
import { useUserStore } from '@/store';
import { all } from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';
import { IEditorConfig } from '@wangeditor/editor'


// 编辑器实例，必须用 shallowRef
const user = useUserStore();
const editorRef = shallowRef()
const valueHtml = ref('')
const authHeaders = { };
const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

const emit = defineEmits(['update:modelValue']);

//定义mode
const props = defineProps({
  mode: {
    type: String,
    default: 'default',
  },
  modelValue: {
    type: String,
    default: '',
  },
  fileType: {
        type: Array,
        default: () => ["png", "jpg", "jpeg"],
    },
  placeholder: {
    type: String,
    default: '请输入内容...',
  },

});
//设置监听事件
watch(() => props.modelValue, (val) => {
  valueHtml.value = val;
},{immediate: true,deep: true});

//编辑器值发生变化时，会动态绑定到 v-model中
const handleChange =(editor:IDomEditor) => {
  emit('update:modelValue', editor.getHtml());
}

const toolbarConfig = {}
const editorConfig = { 
  placeholder: props.placeholder,
  MENU_CONF: {
    uploadImage: {
      server: uploadUrl,
      fieldName: 'file',
      maxFileSize: 5*1024*1024,//5M
      headers: {[user.tokenHead]: user.token},
      allowedFileTypes: ['image/*'],
      onBeforeUpload: (file: File) => {
        for(const fileKey in file){
          if(!file[fileKey].type.startsWith('image/')) {
            MessagePlugin.error(`${t('components.upload.fileType')}!`);
            return false;
          }
        } 
        return file;
      },
        customInsert(res: any, insertFn: InsertFnType) {
          console.log(res);
          insertFn(fileView(res.data),res.data,fileView(res.data));
  },
    },
    uploadVideo: {
      server: uploadUrl,
      fieldName: 'file',
      maxFileSize: 50*1024*1024,//50M
      headers: {[user.tokenHead]: user.token},
      customInsert(res: any, insertFn: InsertFnType) {
          insertFn(fileView(res.data));
      }
}
  },
}

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
    })
</script>
<script lang="ts">
export default defineComponent({
  name: 'SEditor'
});
</script>